package com.hcloud.uploadsdk;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PhoneUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cloud.wolibrary.WoLib;
import com.cloud.wolibrary.backup.BackupGalleryManager;
import com.cloud.wolibrary.bean.BackupBean;
import com.cloud.wolibrary.bean.BackupType;
import com.cloud.wolibrary.bean.FileBean;
import com.cloud.wolibrary.bean.UploadProgress;
import com.cloud.wolibrary.callback.IBackupResultCallback;
import com.cloud.wolibrary.callback.OperatorCallback;

import java.io.File;
import java.util.List;


public class BackupActivity extends AppCompatActivity implements View.OnClickListener {

    private CheckBox mCheckImg;
    private CheckBox mCheckVideo;
    private Button mBtPauseOrRestart;
    private TextView mTvNum;
    private ProgressDialog mProgressDialog;
    private EditText etCode;
    private EditText etPhone;
    private MyUploadStrategy myUploadStrategy;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_backup);
        mProgressDialog = new ProgressDialog(this);

        mCheckImg = findViewById(R.id.check_img);
        mCheckVideo = findViewById(R.id.check_video);
        mTvNum = findViewById(R.id.tv_num);
        mBtPauseOrRestart = findViewById(R.id.bt_pause);

        findViewById(R.id.bt_start).setOnClickListener(this);
        findViewById(R.id.bt_pause).setOnClickListener(this);
        findViewById(R.id.bt_close).setOnClickListener(this);

        etCode = findViewById(R.id.et_code);
        etPhone = findViewById(R.id.et_phone);

        myUploadStrategy = new MyUploadStrategy();
        WoLib.getInstance().setUploadStrategy(myUploadStrategy);

        findViewById(R.id.bt_filter).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != myUploadStrategy){
                    StringBuffer buffer = new StringBuffer();
                    List<File> fileList = myUploadStrategy.getFilterBackupList();
                    for (File file: fileList){
                        buffer.append(file.getName()).append("\n");
                    }
                    if (buffer.length() != 0){
                        ToastUtils.showShort(buffer.toString());
                    }
                }
            }
        });

        //备份监听回调
        BackupGalleryManager.getInstance().setOnIBackupResultCallBack(new IBackupResultCallback() {

            @Override
            public void backupFileProgress(FileBean fileBean, UploadProgress uploadProgress) {
                Log.d("wolib", "backupFileProgress fileBean name  " + fileBean.fileName + " uploadProgress  " + uploadProgress.getProgress());

            }

            @Override
            public void backupProgress(FileBean fileBean, int totalCount, int unBackupCount) {
                mTvNum.setText("剩余：" + unBackupCount + "/" + totalCount);
                Log.d("wolib", "backupProgress totoal " + totalCount + " unbackup count " + unBackupCount);
                // fileBean 在初始状态为null  需判空处理
                if (null != fileBean) {
//                    WoUtils.d("time:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Long.valueOf(fileBean.getLastModified())));
                }
            }

            @Override
            public void backupComplete() {
                //所有文件备份完成
                mTvNum.setText("剩余：0");
            }

            @Override
            public void backupError(int backupStatus, String errorCode, String errorMsg) {
                //backupStatus   0 无状态 1 初始化中(验证中) 2 文件扫描中 3 备份中 4 暂停中 5 备份全部完成
//                WoUtils.d("errorCode:" + errorCode + ",errorMsg:" + errorMsg);
                Log.d("wolib", "backupError backupStatus " + backupStatus + " errorCode " + errorCode + " errorMsg " + errorMsg);

            }
        });

        //获取备份状态
        BackupBean backupBean = BackupGalleryManager.getInstance().getBackupBean();
//        WoUtils.d("backupBean:" + backupBean.toString());
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_start:
                start();
                break;
            case R.id.bt_pause:
                pauseOrRestart();
                break;
            case R.id.bt_close:
                close();
                break;
        }
    }


    private void start() {
        //这里demo 设备唯一code只是测试，正式环境中请获取真实设备唯一code
        String deviceCode = etCode.getText().toString();
//        String phone = etPhone.getText().toString();
        if (TextUtils.isEmpty(deviceCode)) {
            ToastUtils.showShort("设备号不能为空");
            return;
        }
//        if (TextUtils.isEmpty(phone)) {
//            ToastUtils.showShort("token不能为空");
//            return;
//        }
        if (!mCheckImg.isChecked() && !mCheckVideo.isChecked()) {
            ToastUtils.showShort("--未选择照片或视频--");
            return;
        }

//        WoLib.getInstance().setToken(phone, null);

        BackupType backupType = null;//0 全部  1 照片  2 视频
        if (mCheckImg.isChecked() && mCheckVideo.isChecked()) {
            backupType = BackupType.ALL;
        } else if (mCheckImg.isChecked()) {
            backupType = BackupType.IMAGE;
        } else if (mCheckVideo.isChecked()) {
            backupType = BackupType.VIDEO;
        }
        mBtPauseOrRestart.setText("暂停");
        mProgressDialog.show();//防止频繁操作


        LogUtils.e("--select--" + deviceCode + " backup type" + backupType);

        BackupGalleryManager.getInstance().start(deviceCode, backupType, new OperatorCallback() {
            @Override
            public void onOperatorComplete() {
                mProgressDialog.dismiss();
            }
        });
    }

    private void pauseOrRestart() {
        String text = mBtPauseOrRestart.getText().toString();
        if ("暂停".equals(text)) {
            BackupGalleryManager.getInstance().pause(new OperatorCallback() {
                @Override
                public void onOperatorComplete() {
                    mBtPauseOrRestart.setText("继续");
                }
            });
        } else if ("继续".equals(text)) {
            BackupGalleryManager.getInstance().resume(new OperatorCallback() {
                @Override
                public void onOperatorComplete() {
                    mBtPauseOrRestart.setText("暂停");
                }
            });
        }
    }

    private void close() {
        BackupGalleryManager.getInstance().cancel(new OperatorCallback() {
            @Override
            public void onOperatorComplete() {
                mBtPauseOrRestart.setText("暂停/继续");
                mTvNum.setText("剩余：0");
                if (null != myUploadStrategy){
                    myUploadStrategy.getFilterBackupList().clear();
                }
            }
        });
    }
}